# coding:utf-8

import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
import json
import torndb
import time
import tornado.gen
import os

from tornado.options import options
from tornado.web import RequestHandler
from tornado.httpclient import AsyncHTTPClient
from tornado.websocket import WebSocketHandler

tornado.options.define("port", default=8000, type=int, help="run server on the given port")


class IndexHandler(RequestHandler):
    def get(self):
        self.render("index.html")


class Application(tornado.web.Application):
    """"""
    def __init__(self, *args, **kwargs):
        super(Application, self).__init__(*args, **kwargs)
        self.db = torndb.Connection(
            host="127.0.0.1",
            database="itcast",
            user="root",
            password="mysql"
        )


class ChatHandler(WebSocketHandler):

    users = []

    def open(self):
        ChatHandler.users.append(self)
        for user in ChatHandler.users:
            user.write_message(u"%s 上线了" % self.request.remote_ip)

    def on_message(self, message):
        for user in ChatHandler.users:
            user.write_message(u"%s 说: %s" % (self.request.remote_ip, message))

    def on_close(self):
        ChatHandler.users.remove(self)
        for user in ChatHandler.users:
            user.write_message(u"%s 下线了" % self.request.remote_ip)

    def check_origin(self, origin):
        return True

if __name__ == "__main__":
    tornado.options.parse_command_line()
    settings = {
        "debug": True,
        "cookie_secret": "CYUqMIFfRxOpPn4p1mJZBL3wgQJfDUwrlCM+JdC7atQ=",
        "template_path":os.path.join(os.path.dirname(__file__), "template")
    }
    app = Application(
        [
            (r"/", IndexHandler),
            (r"/chat", ChatHandler),
        ],
        **settings
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()